package com.doge.walknovel.business.reader

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.LinearLayoutManager
import com.doge.wnpro.R
import com.doge.walknovel.analysis.analysisEvent
import com.doge.walknovel.analysis.read_start
import com.doge.walknovel.analysis.read_unlock_chapter
import com.doge.walknovel.api.model.ChapterInfo
import com.doge.walknovel.business.home.library.LibraryRepository
import com.doge.walknovel.business.novel.NovelRefer
import com.doge.walknovel.business.reader.menus.ReaderHelper
import com.doge.walknovel.business.reader.menus.ReaderMenuFragment
import com.doge.walknovel.core.BaseActivity
import com.doge.walknovel.core.account.AccountHelper
import com.doge.walknovel.core.account.AppUserViewModel
import com.doge.wnpro.databinding.ActivityReaderBinding
import com.doge.walknovel.utils.*

class ReaderActivity : BaseActivity() {
    private val binding by lazy { ActivityReaderBinding.inflate(layoutInflater) }
    private val referId: Int? by lazy { intent?.getIntExtra(NovelRefer.EXTRA_REFER_ID, 0) }
    private val refer by lazy { intent?.getStringExtra(NovelRefer.EXTRA_REFER)!! }
    private val novelId by lazy { intent?.getIntExtra(EXTRA_NOVEL_ID, 0)!! }
    private val chapterId: Int by lazy { intent?.getIntExtra(EXTRA_CHAPTER_ID, 0)!! }
    private val viewModel: ReaderViewModel by viewModels { ReaderViewModelFactory(novelId) }
    private val adapter by lazy { ReaderAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        analysisEvent(read_start)
        systemWindowInsetsTop.observe(this) {
            binding.recyclerView.updatePadding(top = 15.dp + it)
        }
        supportFragmentManager.beginTransaction()
            .replace(R.id.menusFrame, ReaderMenuFragment.newInstance(novelId, refer, referId))
            .commitAllowingStateLoss()

        ReaderHelper.setListener(object : ReaderHelper.Listener {
            override fun onSizeChanged(value: Int) {
                viewModel.changeSize(value)
            }

            override fun onBgColorChanged(value: String) {
                binding.bookGesture.setBackgroundColor(getColor(value))
                viewModel.changeBgColor(value)
            }

            override fun onLightChanged(value: Boolean) {
                val color = if (value) ReaderHelper.bgColor else "#121212"
                viewModel.changeLight(value)
                binding.bookGesture.setBackgroundColor(getColor(color))
            }

            override fun onTypefaceChanged(value: Typeface) {
                viewModel.changeTypeface(value)
            }
        })

        binding.bookGesture.addListener(object : NovelGestureLayout.Listener {
            override fun onCenterClick() {
                viewModel.displayMenus()
            }
        })
        binding.guide.setOnClickCallback {
            viewModel.displayMenus()
        }

        val color = if (ReaderHelper.light) ReaderHelper.bgColor else "#121212"
        binding.bookGesture.setBackgroundColor(getColor(color))

        binding.recyclerView.itemAnimator = null
        binding.recyclerView.layoutManager = LinearLayoutManager(binding.recyclerView.context)
        binding.recyclerView.adapter = adapter
        ReaderAdapterObserver(binding.recyclerView).also {
            adapter.registerAdapterDataObserver(it)
        }
        adapter.setListener(::handleAdapterCallback)

        viewModel.dataList.observe(this) {
            adapter.submitList(it)
            log("ChapterCacheHelper data submitList ${it.size}")
            binding.loading.isVisible = it.isNullOrEmpty()
        }
        viewModel.menuScrollToChapterId.observe(this) {
            it?.let(::scrollToChapterId)
        }
        scrollToChapterId(chapterId)

        viewModel.requestChapters()
    }

    override fun finish() {
        super.finish()
        AppUserViewModel.get().requestSelfInfo() // refresh coin by unlock chapter
        LibraryRepository.get().requestMyLib() // refresh percent. todo opt
    }

    override fun onDestroy() {
        super.onDestroy()
        ReaderHelper.setListener(null)
        adapter.setListener(null)
        binding.recyclerView.adapter = null
    }

    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            RECORD_CHAPTER -> viewModel.requestRecordChapter(item as? ChapterInfo?)
            UNLOCK -> {
                AccountHelper.requiredLogin {
                    analysisEvent(read_unlock_chapter)
                    NovelGestureLayout.postInterceptTouchEvent()
                    viewModel.requestUnlock(item as? ChapterInfo?)
                }
            }
        }
    }

    private fun scrollToChapterId(chapterId: Int?) {
        log("reader scrollToChapterId $chapterId")
        viewModel.redirectToChapterId(chapterId)
    }

    companion object {
        private const val EXTRA_NOVEL_ID = "novelId"
        private const val EXTRA_CHAPTER_ID = "chapterId"
        fun start(context: Context?, novelId: Int?, chapterId: Int?, refer: String, referId: Int? = null) {
            if (context == null) return
            if (novelId == null) return
            if (chapterId.isNullOrZero()) return
            AccountHelper.requiredLogin {
                context.startActivity(Intent(context, ReaderActivity::class.java).apply {
                    putExtra(EXTRA_NOVEL_ID, novelId)
                    putExtra(EXTRA_CHAPTER_ID, chapterId)

                    putExtra(NovelRefer.EXTRA_REFER, refer)
                    referId?.let { putExtra(NovelRefer.EXTRA_REFER_ID, it) }
                })
            }
        }
    }
}